package com.wgts.wgts.mvp.view.activity.wgtshome;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.wgts.wgts.R;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.eventbus.LoginEvenBus;
import com.wgts.wgts.control.recycleview.CustomLineaLayoutManager;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerWgtsHomePageFragmentComponent;
import com.wgts.wgts.dagger.module.WgtsHomePageFragmentModule;
import com.wgts.wgts.mvp.presenter.IWgtsHomePageFragmentPresenter;
import com.wgts.wgts.mvp.view.IWgtsHomePageFragmentView;
import com.wgts.wgts.mvp.view.activity.goodsinfo.JDGoodinfoActivity;
import com.wgts.wgts.mvp.view.activity.homapge.BannerViewHolder;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.message.MessageDetailsActivity;
import com.wgts.wgts.mvp.view.activity.webactivity.WebActivity;
import com.wgts.wgts.netmodle.resp.AppModleEntity;
import com.wgts.wgts.netmodle.resp.ArticleEntity;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.CustomImageView;
import com.wgts.wgts.tools.MoHuGlide;
import com.wgts.wgts.tools.Tools;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class WgtsHomePageFragment extends LazyBaseFragment implements IWgtsHomePageFragmentView {

    Unbinder unbinder;
    @BindView(R.id.img_msg)
    ImageView imgMsg;
    @BindView(R.id.linear_title)
    LinearLayout linearTitle;
    @BindView(R.id.mz_banner)
    MZBannerView mzBanner;
    @BindView(R.id.img_get_money)
    ImageView imgGetMoney;
    @BindView(R.id.tv_get_money)
    TextView tvGetMoney;
    @BindView(R.id.linear_h51)
    LinearLayout linearH51;
    @BindView(R.id.img_qr_code)
    ImageView imgQrCode;
    @BindView(R.id.tv_qr_code)
    TextView tvQrCode;
    @BindView(R.id.linear_h52)
    LinearLayout linearH52;
    @BindView(R.id.img_put_adver)
    ImageView imgPutAdver;
    @BindView(R.id.tv_put_adver)
    TextView tvPutAdver;
    @BindView(R.id.linear_h53)
    LinearLayout linearH53;
    @BindView(R.id.img_market)
    ImageView imgMarket;
    @BindView(R.id.tv_market)
    TextView tvMarket;
    @BindView(R.id.linear_market)
    LinearLayout linearMarket;
    @BindView(R.id.img_kefu)
    ImageView imgKefu;
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    @BindView(R.id.linear_h54)
    LinearLayout linearH54;
    @BindView(R.id.gif_webView)
    ImageView gifWebView;
    @BindView(R.id.img_1)
    ImageView img1;
    @BindView(R.id.img_2)
    ImageView img2;
    @BindView(R.id.img_3)
    ImageView img3;
    @BindView(R.id.img_friend)
    ImageView imgFriend;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.none_data_ly)
    LinearLayout noneDataLy;
    @BindView(R.id.net_error_ly)
    LinearLayout netErrorLy;
    private CustomLineaLayoutManager linearLayoutManager;

    private WgtsHomePageAdapter wgtsHomePageAdapter;

    private List<ArticleEntity> articleEntities;

    private List<AppModleEntity.AppModleResult> appModleResults;


    @Inject
    IWgtsHomePageFragmentPresenter presenter;

    @Override
    protected void loadData() {
        initView();
    }

    @Override
    public void init() {

        //mzBanner.setPages();
        DaggerWgtsHomePageFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .wgtsHomePageFragmentModule(new WgtsHomePageFragmentModule(this))
                .build()
                .inject(this);

        articleEntities = new ArrayList<>();
        wgtsHomePageAdapter = new WgtsHomePageAdapter(getContext(), articleEntities);

    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.wgts_home_page_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginEvenBus event) {
        presenter.initDataView();
    };

    private void initView() {

        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadmore(true);

        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.moreMoreArtric();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.initArtrict();
                presenter.initDataView();
            }
        });

//        DisplayMetrics outMetrics = Tools.metrics(getActivity());
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(outMetrics.widthPixels, (int) (outMetrics.widthPixels * 0.45));
//        mzBanner.setLayoutParams(layoutParams);
//        //Tools.setViewMargin(mzBanner, true, 0, 0, 0, 10);
        linearLayoutManager = new CustomLineaLayoutManager(getContext());
        recycleView.setLayoutManager(linearLayoutManager);
        recycleView.setAdapter(wgtsHomePageAdapter);

        wgtsHomePageAdapter.setOnClickListener(new WgtsHomePageAdapter.OnClickListener() {
            @Override
            public void onClick(View view, int i) {
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra(WebActivity.TITLE, "详情");
                intent.putExtra(WebActivity.ACTION_URL, articleEntities.get(i).url);
                startActivity(intent);
            }
        });

        presenter.initArtrict();

        presenter.initDataView();

    }

    @OnClick({R.id.linear_market, R.id.net_error_ly, R.id.img_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.linear_market:
                jumpProductActivity(WgtsNomalMarketActivity.class);
                break;

            case R.id.net_error_ly:
                presenter.initArtrict();
                break;
            case R.id.img_msg:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
                    jumpProductActivity(MessageDetailsActivity.class);
                } else {
                    Intent intent2 = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent2);
                }
                break;
        }
    }

    private void jumpProductActivity(Class activity) {
        Intent intent = new Intent(getContext(), activity);
        getActivity().startActivity(intent);
    }

    @Override
    public void onError(int status, String msg) {
        smartRefreshLayout.finishLoadmore();
        smartRefreshLayout.finishRefresh();
    }

    @Override
    public void initArtric(List<ArticleEntity> articleEntities, boolean noMore) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.setEnableLoadmore(!noMore);
        wgtsHomePageAdapter.setNoMore(noMore);
        this.articleEntities.clear();
        this.articleEntities.addAll(articleEntities);
        wgtsHomePageAdapter.notifyDataSetChanged();
    }

    @Override
    public void moreArtric(List<ArticleEntity> articleEntities, boolean noMore) {
        smartRefreshLayout.finishLoadmore();
        smartRefreshLayout.setEnableLoadmore(!noMore);
        wgtsHomePageAdapter.setNoMore(noMore);
        this.articleEntities.addAll(articleEntities);
        wgtsHomePageAdapter.notifyDataSetChanged();
    }

    @Override
    public void initResult(List<AppModleEntity> appModleEntities) {
        smartRefreshLayout.finishRefresh();

        Log.d("", "");
        for (AppModleEntity entity : appModleEntities) {
            if (entity.type.equals("INDEX_BANNER")) {
                initBanner(entity.result);
            }
            if (entity.type.equals("SHOW_MENU")) {
                //ToDO
                initRecycleViewEntry(entity.result);
            }
            if (entity.type.equals("NEW_WELFARE")) {
                initWebView(entity.result);
            }
            if (entity.type.equals("PARTNER")) {
                initFriend(entity.result);
            }
            if (entity.type.equals("PRODUCT_PROMOTION")) {
                initProduct(entity.result);
            }
        }
    }


    private void initBanner(final List<AppModleEntity.AppModleResult> banners) {


        DisplayMetrics outMetrics = Tools.metrics(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(outMetrics.widthPixels, (int) (outMetrics.widthPixels * 0.45));
        mzBanner.setLayoutParams(layoutParams);
        //Tools.setViewMargin(mzBanner, true, 0, 0, 44, 10);

        mzBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {

                Intent intent = null;

                if (banners.get(i).actionUrlType.equals("0")) {
                    intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra(WebActivity.ACTION_URL, banners.get(i).actionUrl);
                    intent.putExtra(WebActivity.TITLE, banners.get(i).name);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(banners.get(i).actionUrl);
                        switch (jsonObject.getString("code")) {
                            case "5":
                                intent = new Intent(getActivity(), JDGoodinfoActivity.class);
                                intent.putExtra(JDGoodinfoActivity.PRODUCT_ID, jsonObject.getString("param"));
                                intent.putExtra(JDGoodinfoActivity.JOIN_TYPE, JDGoodinfoActivity.NOMAL);
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (intent != null) {
                    startActivity(intent);
                }
            }
        });

        mzBanner.setPages(banners, new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mzBanner.start();


    }


    private void initRecycleViewEntry(final List<AppModleEntity.AppModleResult> appModleResults) {

        this.appModleResults = appModleResults;

        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(0).sourceUrl, R.mipmap.icon_function_money, imgGetMoney);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(1).sourceUrl, R.mipmap.icon_function_qr, imgQrCode);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(2).sourceUrl, R.mipmap.icon_function_banner, imgPutAdver);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(3).sourceUrl, R.mipmap.icon_function_mohu, imgMarket);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(4).sourceUrl, R.mipmap.icon_function_service, imgKefu);

        tvGetMoney.setText(appModleResults.get(0).name);
        tvQrCode.setText(appModleResults.get(1).name);
        tvPutAdver.setText(appModleResults.get(2).name);
        tvMarket.setText(appModleResults.get(3).name);
        tvKefu.setText(appModleResults.get(4).name);

        linearH51.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (appModleResults.get(0).actionUrlType.equals("0")){
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra(WebActivity.TITLE, appModleResults.get(0).name);
                    intent.putExtra(WebActivity.ACTION_URL, appModleResults.get(0).actionUrl);
                    startActivity(intent);
                }
            }
        });

        linearH52.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(AppInfor.getInstance().getRefreshToken().equals("")){
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                }else{

                    if (appModleResults.get(1).actionUrlType.equals("0")){

                        String actionUrl = appModleResults.get(1).actionUrl;


                        if(AppInfor.getInstance().getUserState() > 0){
                            if(appModleResults.get(1).actionUrl.contains("?")){
                                actionUrl = appModleResults.get(1).actionUrl + "&" + "userCode=" + android.util.Base64.encodeToString(AppInfor.getInstance().getUserYQCode().getBytes(), android.util.Base64.NO_WRAP);
                            }else {
                                actionUrl = appModleResults.get(1).actionUrl + "?" + "userCode=" + android.util.Base64.encodeToString(AppInfor.getInstance().getUserYQCode().getBytes(), android.util.Base64.NO_WRAP);
                            }
                        }

                        Intent intent = new Intent(getContext(), WebActivity.class);
                        intent.putExtra(WebActivity.TITLE, appModleResults.get(1).name);
                        intent.putExtra(WebActivity.ACTION_URL, actionUrl);
                        startActivity(intent);
                    }
                }
            }
        });

        linearH53.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (appModleResults.get(2).actionUrlType.equals("0")){
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra(WebActivity.TITLE, appModleResults.get(2).name);
                    intent.putExtra(WebActivity.ACTION_URL, appModleResults.get(2).actionUrl);
                    startActivity(intent);
                }
            }
        });



        linearH54.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (appModleResults.get(4).actionUrlType.equals("0")){
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtra(WebActivity.TITLE, appModleResults.get(4).name);
                    intent.putExtra(WebActivity.ACTION_URL, appModleResults.get(4).actionUrl);
                    startActivity(intent);
                }
            }
        });

    }

    private void initWebView(final List<AppModleEntity.AppModleResult> appModleResults) {

        CustomImageView.getInstance().customImage(getContext(), gifWebView, (164 / (double) 750));

        if (appModleResults != null && appModleResults.size() >= 2) {
            if (AppInfor.getInstance().getUserState() > 0) {
                MoHuGlide.getInstance().loadGif(getContext(), appModleResults.get(1).sourceUrl, gifWebView);

                gifWebView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppModleEntity.AppModleResult appModleResult = appModleResults.get(1);

                        String actionUrl = appModleResult.actionUrl;

                        if (appModleResult.actionUrlType.equals("0")) {
                            //TODO go to web View;

                            if(appModleResult.actionUrl.contains("?")){
                                actionUrl = appModleResult.actionUrl + "&" + "userCode=" + android.util.Base64.encodeToString(AppInfor.getInstance().getUserYQCode().getBytes(), android.util.Base64.NO_WRAP);
                            }else {
                                actionUrl = appModleResult.actionUrl + "?" + "userCode=" + android.util.Base64.encodeToString(AppInfor.getInstance().getUserYQCode().getBytes(), android.util.Base64.NO_WRAP);
                            }
                            Log.e("=====================>", actionUrl);

                            Intent intent = new Intent(getActivity(), WebActivity.class);
                            intent.putExtra(WebActivity.ACTION_URL, actionUrl);
                            intent.putExtra(WebActivity.TITLE, appModleResult.name);
                            startActivity(intent);
                        }
                    }
                });

            } else {
                MoHuGlide.getInstance().loadGif(getContext(), appModleResults.get(0).sourceUrl, gifWebView);


                gifWebView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        jumpToSpecial(appModleResults.get(0));
                    }
                });
            }
        }
    }

    private void initFriend(List<AppModleEntity.AppModleResult> appModleResults) {
        CustomImageView.getInstance().customImage(getContext(), imgFriend, (204 / (double) 375));
        MoHuGlide.getInstance().glideImg(getActivity(), appModleResults.get(0).sourceUrl, imgFriend);
    }


    private void jumpToSpecial(AppModleEntity.AppModleResult appModleResult) {
        if (appModleResult.actionUrlType.equals("0")) {
            //TODO go to web View;
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra(WebActivity.ACTION_URL, appModleResult.actionUrl);
            intent.putExtra(WebActivity.TITLE, appModleResult.name);
            startActivity(intent);
        }
    }

    private void initProduct(final List<AppModleEntity.AppModleResult> appModleResults) {
       MoHuGlide.getInstance().glideImg(getActivity(), appModleResults.get(0).sourceUrl, img1);
        MoHuGlide.getInstance().glideImg(getActivity(), appModleResults.get(1).sourceUrl, img2);
        MoHuGlide.getInstance().glideImg(getActivity(), appModleResults.get(2).sourceUrl, img3);

        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToSpecial(appModleResults.get(0));
            }
        });
        img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToSpecial(appModleResults.get(1));
            }
        });
        img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToSpecial(appModleResults.get(2));
            }
        });
    }
}
